package com.dtease.agent.sse.server.config;

import io.netty.channel.ChannelOption;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.boot.web.reactive.server.ReactiveWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.config.PathMatchConfigurer;
import org.springframework.web.reactive.config.WebFluxConfigurer;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
* @description WebFlux配置类
* @author chentl
* @class WebFluxConfig
* @package com.dtease.agent.sse.server.config
* @since 2025/5/4 08:37
*/
@Configuration
public class WebFluxConfig implements WebFluxConfigurer {

    public static final String WEB_API_PREFIX = "/ai";
    @Resource
    private  NettyProperties nettyProperties;

    @Override
    public void configurePathMatching(PathMatchConfigurer configurer) {
        // 所有路由添加 /api 前缀
        configurer.addPathPrefix(WEB_API_PREFIX, c -> true);
        // 禁用尾部斜杠匹配
        configurer.setUseTrailingSlashMatch(false);
        //  禁用路径大小写敏感匹配
        configurer.setUseCaseSensitiveMatch(false);
    }

    @Bean
    public WebServerFactoryCustomizer<ReactiveWebServerFactory> webServerCustomizer() {
        return factory -> {
            if (factory instanceof NettyReactiveWebServerFactory) {
                NettyReactiveWebServerFactory nettyFactory = (NettyReactiveWebServerFactory) factory;

                nettyFactory.addServerCustomizers(tcpServer -> tcpServer
                        // 设置连接超时时间（毫秒）
                        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyProperties.getConnectTimeout())
                        .doOnConnection(conn -> conn
                                // 设置读取超时（单位：秒）
                                .addHandlerLast(new ReadTimeoutHandler(nettyProperties.getReadTimeout(), TimeUnit.SECONDS))
                                // 设置写入超时（单位：秒）
                                .addHandlerLast(new WriteTimeoutHandler(nettyProperties.getWriteTimeout(), TimeUnit.SECONDS))
                        ));
            }
        };
    }
}